<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <style>
    input {
        width: 200px;
        height: 16px;
        padding: 6px 12px;
        font-size: 14px;
        line-height: 1.42857143;
        color: #555;
        background-color: #fff;
        background-image: none;
        border: 1px solid #ccc;
        border-radius: 4px;
        /*        outline: none;*/
        box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    }
    .formscontent span{
			margin-right: 40px;
    }
    .validate_message {
        font-size: 16px;
        color: #B4B4B4;
    }
    
    .bsuccess {
        border-color: #5cb85c!important;
    }
    
    .bfail {
        border-color: #d9534f!important;
    }
    
    .success {
        color: #5cb85c!important;
    }
    
    .fail {
        color: #d9534f!important;
    }
    .btn {
        display: inline-block;
        padding: 6px 12px;
        margin-bottom: 0;
        font-size: 14px;
        font-weight: 400;
        line-height: 1.42857143;
        text-align: center;
        white-space: nowrap;
        vertical-align: middle;
        -ms-touch-action: manipulation;
        touch-action: manipulation;
        cursor: pointer;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        background-image: none;
        border: 1px solid transparent;
        border-radius: 4px;
    }
    .btn-primary {
        color: #fff;
        background-color: #337ab7;
        border-color: #2e6da4;
    }
    </style>
</head>

<body>
    <h1></h1>
    <script>
    /*
    	表单自动生成工厂v1.0.0
			使用了单例模式。
			分两种情况，一种是双重验证，比如重复密码验证
								一种是单层验证，比如格式验证
			暂时只写了input生成，代码思路应该还是清楚的,后续添加应该还是方便的。。。

     */

    var data = [{
        label: '名字',
        name: 'name',
        type: 'input',
        validator: function(name) {
            return checkLen(name) >= 4 && checkLen(name) <= 16;
        },
        rules: '必填，长度为4-16个字符',
        success: '格式正确',
        fail: '格式错误'
    }, {
        label: '密码',
        name: 'password',
        type: 'password',
        validator: function(password) {
            return checkLen(password) >= 4 && checkLen(password) <= 16;
        },
        rules: '必填，长度为4-16个字符',
        success: '格式正确',
        fail: '格式错误'
    },{
        label: '重复密码',
        name: 'verifypassword',
        type: 'password',
        validator: function(password) {
            return verifypassword("password",password);
        },
        rules: '再次输入相同密码',
        success: '输入相同',
        fail: '两次密码输入不一致,请重新输入'
    },{
        label: '邮箱',
        name: 'email',
        type: 'input',
        validator: function(email) {
            return checkRegex(email,/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
        },
        rules: '必填,请输入合法邮箱',
        success: '格式正确',
        fail: '格式错误'
    },{
        label: '手机',
        name: 'phone',
        type: 'input',
        validator: function(phone) {
            return checkRegex(phone,/^0?1[3|4|5|8][0-9]\d{8}$/);
        },
        rules: '必填,请输入合法手机号码',
        success: '格式正确',
        fail: '格式错误'
    }

    ];

    window.onload = function() {
        for (var i = 0 ;i < data.length ;i++) {
            formsFactory(data[i]);
        }
        var el = document.createElement("div");
        el.className = "submit btn btn-primary";
        el.innerText = "提交";
        el.addEventListener('click', function() {
            checkAll();
        }, false);
        document.body.appendChild(el);
    }

    function checkLen(string) {
        var len = 0;
        for (var i = string.length - 1; i >= 0; i--) {
            //汉字长度为2
            if (/^[\u4e00-\u9fa5]+$/.test(string[i])) {
                len = len + 2;
            } else {
                len++;
            }

        }
        return len;

    }
    function verifypassword(lastpassId,string){
    	var lastpass = document.querySelector('#'+lastpassId).value;
    	return string == lastpass;
    }

    function checkRegex(string, regex) {
        var validated = string;
        return regex.test(validated);
    }

    function checkAll() {
        var List = document.querySelectorAll("input");
        var flag = 0;
        console.log(List.length)
        for (var i = List.length - 1; i >= 0; i--) {
            if (List[i].className == 'bsuccess') {
                flag++;
            }
        }

        if (flag == List.length) {
            alert("提交成功!")
        } else {
            alert("提交失败!");
        }

    }


    function formsFactory(data) {
        var config = data;

        var valiadate = {
            arrangement: {
                label: config.label, // 表单标签
                name: config.name, // 表单名称
                type: config.type, // 表单类型
                validator: config.validator, // 表单验证规
                rules: config.rules, // 填写规则提示
                success: config.success, // 验证通过提示
                fail: config.fail // 验证失败提示
            },

            generateInput: function(type) {
                var that = this;
                var container = document.createElement("div")
                container.className = 'formscontent';
                var span = document.createElement("span");
                span.innerText = that.arrangement.label;

                var p = document.createElement("p");
                p.className = 'validate_message';

                var input = document.createElement("input");
                input.name = that.arrangement.name;
                input.type = that.arrangement.type;
                input.id = that.arrangement.name;
                input.addEventListener('focus', function() {
                  p.innerText = that.arrangement.rules;
                }, false);

                input.addEventListener('blur', function() {
                	  var validate = '';
                		if(type == 'single'){
                			validate = that.arrangement.validator(this.value);
                		}else if(type == 'verify'){
                			validate = that.arrangement.validator(this.value) && this.value.length!=0;
                		}
                    if (validate) {
                        input.className = 'bsuccess';
                        p.innerText = that.arrangement.label + that.arrangement.success;
                        p.className = 'success';
                    } else if (this.value.length == 0) {
                        input.className = 'bfail';
                        p.innerText = that.arrangement.label + '不能为空';
                        p.className = 'fail';
                    } else {
                        input.className = 'bfail';
                        p.innerText = that.arrangement.fail;
                        p.className = 'fail';
                    }
                }, false);

                container.appendChild(span);
                container.appendChild(input);
                container.appendChild(p);
                document.body.appendChild(container);
            },
            init: function() {
                var that = this;
                //判断类型
                switch (that.arrangement.name) {
                    case 'name':
                        that.generateInput('single');
                        break;
                    case 'password':
                        that.generateInput('single');
                        break;
                    case 'verifypassword':
                        that.generateInput('verify');
                        break;
                    case 'email':
                        that.generateInput('single');
                        break;
                    case 'phone':
                        that.generateInput('single');
                        break;
                }
            }

        }
        return valiadate.init();
    }
    </script>
</body>

</html>
